<template>
	<view class="fix-top-window">
		<view class="uni-header">
			<uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
			<download-excel class="" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
				<button class="uni-button" type="primary" size="mini" style="margin-right: 20px;">导出Excel</button>
			</download-excel>
		</view>
		<view class="uni-container">
			<view class="example-body">
				<uni-datetime-picker v-model="range" returnType="timestamp" type="daterange" @change="dateChange"
					@maskClick="maskClick" />
			</view>
			<view style="margin-top: 30px;">
				<!-- 列表 -->
				<unicloud-db ref="udb" v-slot:default="{data, pagination, loading, error, options}" :options="options"
					collection="account" orderby="createTime desc" field="_id,number,createTime" :getone="false"
					:action="action" :where="where" @load="onqueryload" @error="onqueryerror">
					<view v-if="error" class="error">{{error.message}}</view>
					<uni-list>
						<uni-list-item :title="item.number" v-for="(item, index) in data" :key="index"
							:note="'入库时间:'+formatTime(item.createTime)" thumb="/static/id.png" thumb-size="lg"
							rightText="" />
					</uni-list>
					<view v-if="loading" class="loading">加载中...</view>
				</unicloud-db>
			</view>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database()
	// 分页配置
	const pageSize = 6
	const pageCurrent = 1
	export default {
		data() {
			return {
				options: {

				},
				action: '',
				where: {}, // 类型为对象或字符串
				range: [],
				exportExcel: {
					"filename": "账号"+new Date().toLocaleString()+".xls",
					"type": "xls",
					"fields": {
						"账号ID": "number",
						"入库时间": "createTimeStr"
					}
				},
				exportExcelData: [],
			}
		},
		onPullDownRefresh() { // 下拉刷新
			try {
				// 等待 loadData 异步操作完成（需确保 udb 组件支持 Promise 风格调用）
				uni.showLoading({
					title: '加载中'
				}); // 显示加载提示
				this.$refs.udb.loadData({
					clear: true
				});
				uni.stopPullDownRefresh(); // 停止下拉刷新动画
			} catch (error) {
				console.error('加载数据失败:', error);
			} finally {
				uni.hideLoading(); // 无论成功或失败，最终隐藏加载提示
			}
		},
		onReachBottom() { //滚动到底翻页
			this.$refs.udb.loadMore()
		},
		methods: {
			formatTime(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			onqueryload(data, ended) {
				// 可在此处预处理数据，然后再渲染界面
				this.exportExcelData = []
				data.forEach(e => {
					const item = {
						"number":e.number,
						"createTimeStr":this.formatTime(e.createTime)
					}
					if (item) {
						this.exportExcelData.push(item);
					}
				});
			},
			onqueryerror(e) {
				// 加载数据失败
			},
			dateChange(e) {
				console.log('dateChange事件:', e);
				if (e.length === 2) {
					const [startDate, endDate] = e;
					this.where = {
						createTime: {
							$gte: startDate,
							$lte: endDate + 86400000
						}
					};
				} else {
					// 如果 range 数组长度不为 2，清空 where 条件
					this.where = {};
				}
				this.onPullDownRefresh();
			},
			maskClick(e) {
				console.log('maskClick事件:', e);
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		background-color: #f0f0f0;
	}

	.list-item {
		background-color: #fff;
		margin-bottom: 1px;
		padding: 30px 15px;
	}

	.loading {
		padding: 20px;
		text-align: center;
	}

	.error {
		color: #DD524D;
	}
</style>